{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-2-0299314c131a>:4: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From /home/siweiduo/.local/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please write your own downloading logic.\n",
      "WARNING:tensorflow:From /home/siweiduo/.local/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting /tmp/tensorflow/mnist/input_data/train-images-idx3-ubyte.gz\n",
      "WARNING:tensorflow:From /home/siweiduo/.local/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting /tmp/tensorflow/mnist/input_data/train-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From /home/siweiduo/.local/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.one_hot on tensors.\n",
      "Extracting /tmp/tensorflow/mnist/input_data/t10k-images-idx3-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data/t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From /home/siweiduo/.local/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n"
     ]
    }
   ],
   "source": [
    "# Import the Mnist data set\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "data_dir = '/tmp/tensorflow/mnist/input_data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "n_hidden = 600 # number of notes in hidden layer\n",
    "n_input  = 784\n",
    "n_output = 10"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize Inputs and Outputs\n",
    "x = tf.placeholder(tf.float32, [None, n_input]) \n",
    "y = tf.placeholder(tf.float32, [None, n_output]) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Prepare weights and biases for the network\n",
    "weights = {\n",
    "    'w1': tf.Variable(tf.random_normal([n_input, n_hidden], stddev=0.1)), # weights of hidden layer\n",
    "    'out': tf.Variable(tf.zeros([n_hidden, n_output])) # weights of output\n",
    "}\n",
    "biases = {\n",
    "    'b1': tf.Variable(tf.zeros([n_hidden])),\n",
    "    'out': tf.Variable(tf.zeros([n_output]))\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Forward propagation with relu activation function\n",
    "def multilayer_perceptron(_X, _weights, _biases): \n",
    "    layer_1 = tf.nn.relu(tf.add(tf.matmul(_X, _weights['w1']), _biases['b1'])) # hidden layer 1\n",
    "    return (tf.matmul(layer_1, _weights['out']) + _biases['out']) # output before acting sigmoid activation function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# The prediction obtained from the forward propagation\n",
    "pred = multilayer_perceptron(x, weights, biases) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-8-1ecad8a1bd96>:2: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "\n",
      "Future major versions of TensorFlow will allow gradients to flow\n",
      "into the labels input on backprop by default.\n",
      "\n",
      "See `tf.nn.softmax_cross_entropy_with_logits_v2`.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Define the cost function:\n",
    "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits =pred, labels=y)+tf.contrib.layers.l2_regularizer(0.001)(weights['out'])) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define the gradient flow optimizer\n",
    "optm = tf.train.GradientDescentOptimizer(0.01).minimize(cost) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Compare the labels of the prediction with the real value，reture 'true' if they are the same.\n",
    "correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) \n",
    "# Map 'true' to '1', and then get the mean of all the results\n",
    "accr = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "init = tf.global_variables_initializer()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define parameters\n",
    "training_epochs = 400 # iteration steps\n",
    "batch_size = 100      # choose 100 samples each iteration\n",
    "display_step = 5\n",
    "\n",
    "# Launch the graph\n",
    "sess = tf.Session() # Define a Session\n",
    "sess.run(init)      # Run 'init' in 'sess'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch: 000/400 cost: 0.879941912 TRAIN ACCURACY: 0.900 TEST ACCURACY: 0.881\n",
      "Epoch: 005/400 cost: 0.305808198 TRAIN ACCURACY: 0.880 TEST ACCURACY: 0.922\n",
      "Epoch: 010/400 cost: 0.256525694 TRAIN ACCURACY: 0.940 TEST ACCURACY: 0.932\n",
      "Epoch: 015/400 cost: 0.227202837 TRAIN ACCURACY: 0.910 TEST ACCURACY: 0.939\n",
      "Epoch: 020/400 cost: 0.205770946 TRAIN ACCURACY: 0.910 TEST ACCURACY: 0.944\n",
      "Epoch: 025/400 cost: 0.188864112 TRAIN ACCURACY: 0.880 TEST ACCURACY: 0.949\n",
      "Epoch: 030/400 cost: 0.175178899 TRAIN ACCURACY: 0.970 TEST ACCURACY: 0.953\n",
      "Epoch: 035/400 cost: 0.163872452 TRAIN ACCURACY: 0.920 TEST ACCURACY: 0.956\n",
      "Epoch: 040/400 cost: 0.154459691 TRAIN ACCURACY: 0.960 TEST ACCURACY: 0.958\n",
      "Epoch: 045/400 cost: 0.146471690 TRAIN ACCURACY: 0.950 TEST ACCURACY: 0.961\n",
      "Epoch: 050/400 cost: 0.139472968 TRAIN ACCURACY: 0.970 TEST ACCURACY: 0.962\n",
      "Epoch: 055/400 cost: 0.133642926 TRAIN ACCURACY: 0.970 TEST ACCURACY: 0.965\n",
      "Epoch: 060/400 cost: 0.128331960 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.966\n",
      "Epoch: 065/400 cost: 0.123677941 TRAIN ACCURACY: 0.980 TEST ACCURACY: 0.966\n",
      "Epoch: 070/400 cost: 0.119379317 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.968\n",
      "Epoch: 075/400 cost: 0.115689731 TRAIN ACCURACY: 0.980 TEST ACCURACY: 0.968\n",
      "Epoch: 080/400 cost: 0.112284045 TRAIN ACCURACY: 0.980 TEST ACCURACY: 0.970\n",
      "Epoch: 085/400 cost: 0.109319331 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.970\n",
      "Epoch: 090/400 cost: 0.106480592 TRAIN ACCURACY: 0.980 TEST ACCURACY: 0.971\n",
      "Epoch: 095/400 cost: 0.103872532 TRAIN ACCURACY: 0.950 TEST ACCURACY: 0.973\n",
      "Epoch: 100/400 cost: 0.101545119 TRAIN ACCURACY: 0.970 TEST ACCURACY: 0.973\n",
      "Epoch: 105/400 cost: 0.099372660 TRAIN ACCURACY: 0.970 TEST ACCURACY: 0.972\n",
      "Epoch: 110/400 cost: 0.097346504 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.973\n",
      "Epoch: 115/400 cost: 0.095447414 TRAIN ACCURACY: 0.980 TEST ACCURACY: 0.973\n",
      "Epoch: 120/400 cost: 0.093749302 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.974\n",
      "Epoch: 125/400 cost: 0.092071692 TRAIN ACCURACY: 0.970 TEST ACCURACY: 0.974\n",
      "Epoch: 130/400 cost: 0.090536756 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.975\n",
      "Epoch: 135/400 cost: 0.089055884 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.975\n",
      "Epoch: 140/400 cost: 0.087633913 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.975\n",
      "Epoch: 145/400 cost: 0.086371145 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.976\n",
      "Epoch: 150/400 cost: 0.085101204 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.977\n",
      "Epoch: 155/400 cost: 0.083934896 TRAIN ACCURACY: 0.970 TEST ACCURACY: 0.977\n",
      "Epoch: 160/400 cost: 0.082785011 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.977\n",
      "Epoch: 165/400 cost: 0.081760952 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.976\n",
      "Epoch: 170/400 cost: 0.080715617 TRAIN ACCURACY: 0.970 TEST ACCURACY: 0.977\n",
      "Epoch: 175/400 cost: 0.079728850 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.978\n",
      "Epoch: 180/400 cost: 0.078800035 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.977\n",
      "Epoch: 185/400 cost: 0.077879573 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.977\n",
      "Epoch: 190/400 cost: 0.077067109 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.978\n",
      "Epoch: 195/400 cost: 0.076185903 TRAIN ACCURACY: 0.980 TEST ACCURACY: 0.979\n",
      "Epoch: 200/400 cost: 0.075425309 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.978\n",
      "Epoch: 205/400 cost: 0.074643172 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.979\n",
      "Epoch: 210/400 cost: 0.073865914 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.978\n",
      "Epoch: 215/400 cost: 0.073158384 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.979\n",
      "Epoch: 220/400 cost: 0.072451386 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.979\n",
      "Epoch: 225/400 cost: 0.071789515 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.979\n",
      "Epoch: 230/400 cost: 0.071159716 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.979\n",
      "Epoch: 235/400 cost: 0.070529641 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.979\n",
      "Epoch: 240/400 cost: 0.069891302 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.979\n",
      "Epoch: 245/400 cost: 0.069307603 TRAIN ACCURACY: 0.980 TEST ACCURACY: 0.979\n",
      "Epoch: 250/400 cost: 0.068709437 TRAIN ACCURACY: 0.980 TEST ACCURACY: 0.979\n",
      "Epoch: 255/400 cost: 0.068187756 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.979\n",
      "Epoch: 260/400 cost: 0.067584309 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.980\n",
      "Epoch: 265/400 cost: 0.067112162 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.980\n",
      "Epoch: 270/400 cost: 0.066548935 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.980\n",
      "Epoch: 275/400 cost: 0.066054646 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.980\n",
      "Epoch: 280/400 cost: 0.065550886 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.980\n",
      "Epoch: 285/400 cost: 0.065074443 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.980\n",
      "Epoch: 290/400 cost: 0.064605757 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.980\n",
      "Epoch: 295/400 cost: 0.064128897 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.980\n",
      "Epoch: 300/400 cost: 0.063702517 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.980\n",
      "Epoch: 305/400 cost: 0.063309804 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.980\n",
      "Epoch: 310/400 cost: 0.062852606 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.980\n",
      "Epoch: 315/400 cost: 0.062420071 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.980\n",
      "Epoch: 320/400 cost: 0.061996754 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.980\n",
      "Epoch: 325/400 cost: 0.061633913 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.980\n",
      "Epoch: 330/400 cost: 0.061239803 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.980\n",
      "Epoch: 335/400 cost: 0.060835507 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.979\n",
      "Epoch: 340/400 cost: 0.060445438 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.980\n",
      "Epoch: 345/400 cost: 0.060065369 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.980\n",
      "Epoch: 350/400 cost: 0.059738980 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.981\n",
      "Epoch: 355/400 cost: 0.059387162 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.980\n",
      "Epoch: 360/400 cost: 0.059033135 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.980\n",
      "Epoch: 365/400 cost: 0.058731338 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.980\n",
      "Epoch: 370/400 cost: 0.058352725 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.980\n",
      "Epoch: 375/400 cost: 0.058031126 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.980\n",
      "Epoch: 380/400 cost: 0.057725680 TRAIN ACCURACY: 0.990 TEST ACCURACY: 0.980\n",
      "Epoch: 385/400 cost: 0.057409782 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.980\n",
      "Epoch: 390/400 cost: 0.057054633 TRAIN ACCURACY: 1.000 TEST ACCURACY: 0.980\n",
      "Epoch: 395/400 cost: 0.056759595 TRAIN ACCURACY: 0.980 TEST ACCURACY: 0.980\n",
      "DONE\n"
     ]
    }
   ],
   "source": [
    "# Optimization process\n",
    "for epoch in range(training_epochs):\n",
    "    avg_cost = 0.\n",
    "    total_batch = int(mnist.train.num_examples/batch_size)\n",
    "    # Loop over all batches\n",
    "    for i in range(total_batch):\n",
    "        # Get data from each batch\n",
    "        batch_xs, batch_ys = mnist.train.next_batch(batch_size) \n",
    "        sess.run(optm, feed_dict={x: batch_xs, y: batch_ys})\n",
    "        avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys})/total_batch\n",
    "    # Display logs per epoch step\n",
    "    if epoch % display_step == 0:\n",
    "        train_acc = sess.run(accr, feed_dict={x: batch_xs, y: batch_ys})\n",
    "        test_acc = sess.run(accr, feed_dict={x: mnist.test.images, y: mnist.test.labels})\n",
    "        print(\"Epoch: %03d/%03d cost: %.9f TRAIN ACCURACY: %.3f TEST ACCURACY: %.3f\"\n",
    "              % (epoch, training_epochs, avg_cost, train_acc, test_acc))\n",
    "print(\"DONE\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
